import {Ref} from "vue";
import {Graph} from "@antv/x6";

/**
 * 使用空格键拖动画布
 */
export function useSpacePanning(graphInstance: Ref<Graph>) {
  let graph:Ref<Graph> = graphInstance
  // 空格键绑定的事件
  const bindSpaceKey = () => {
    // console.log('bind space')
    document.querySelector('.x6-graph-scroller')?.addEventListener("keydown", enableSpacePanning)
    document.querySelector('.x6-graph-scroller')?.addEventListener('keyup', disableSpacePanning)
  }

  // 解除空格键绑定
  const unbindSpaceKey = () => {
    // console.log('unbind space')
    document.querySelector('.x6-graph-scroller')?.removeEventListener("keydown", enableSpacePanning)
    document.querySelector('.x6-graph-scroller')?.removeEventListener("keyup", disableSpacePanning)
  }

  // 启用 space + leftMouse 拖拽
  function enableSpacePanning(this:Element, e: Event) {
    // console.log('space down')
    const _e = <KeyboardEvent>e
    if (_e.code === 'Space') {
      graph.value.disableSelection()
      graph.value.lockScroller()
      graph.value.enablePanning()
    }
  }

  // 禁用 space + leftMouse 拖拽。还原
  function disableSpacePanning (this:Element, e: Event) {
    console.log('space up')
    const _e = <KeyboardEvent>e
    if (_e.code === 'Space') {
      graph.value.enableSelection()
      graph.value.disablePanning()
      graph.value.unlockScroller()
    }
  }

  return {
    bindSpaceKey,
    unbindSpaceKey,
  }
}
